<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>标准时间库chrono - 欢迎来到SY的博客</title><meta name="description" content="标准时间库与thread"><meta property="og:title" content="标准时间库chrono" />
<meta property="og:description" content="标准时间库与thread" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" /><meta property="og:image" content="https://acking-you.gitee.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-08-21T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-08-21T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.gitee.io/logo.png"/>

<meta name="twitter:title" content="标准时间库chrono"/>
<meta name="twitter:description" content="标准时间库与thread"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" /><link rel="prev" href="https://acking-you.gitee.io/posts/%C3%A5-%C3%A4%C2%BA%C3%A6%C2%BA%C3%A8%C3%A6%C3%A9/" /><link rel="next" href="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "标准时间库chrono",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.gitee.io\/posts\/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread\/"
        },"genre": "posts","keywords": "标准时间库chrono","wordcount":  3980 ,
        "url": "https:\/\/acking-you.gitee.io\/posts\/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread\/","datePublished": "2022-08-21T00:00:00+00:00","dateModified": "2022-08-21T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "标准时间库与thread"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="欢迎来到SY的博客">欢迎来到SY的博客</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="欢迎来到SY的博客">欢迎来到SY的博客</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/2319540b52ba53f88ff0afbf5cabb92c.png#pic_center"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/2319540b52ba53f88ff0afbf5cabb92c.png#pic_center, https://img-blog.csdnimg.cn/img_convert/2319540b52ba53f88ff0afbf5cabb92c.png#pic_center 1.5x, https://img-blog.csdnimg.cn/img_convert/2319540b52ba53f88ff0afbf5cabb92c.png#pic_center 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/2319540b52ba53f88ff0afbf5cabb92c.png#pic_center"
        title="标准时间库与thread" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">标准时间库chrono</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/cpp%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%BC%82%E6%AD%A5%E4%B8%8E%E5%B9%B6%E5%8F%91/"><i class="far fa-folder fa-fw"></i>CPP多线程异步与并发</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-08-21">2022-08-21</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 3980 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 8 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#前言">前言</a></li>
    <li><a href="#stdchrono标准时间库">std::chrono标准时间库</a></li>
    <li><a href="#1时间间隔duration">1、时间间隔duration</a></li>
    <li><a href="#2时间点time_point">2、时间点time_point</a></li>
    <li><a href="#3时钟clocks">3、时钟clocks</a></li>
    <li><a href="#31system_clock">3.1、system_clock</a></li>
    <li><a href="#32-steady_clock">3.2 、steady_clock</a></li>
    <li><a href="#4duration_cast">4、duration_cast</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h2 id="前言">前言</h2>
<p>在这个专栏中我将会讲解C++11中所用的多线程异步与并发相关的知识点，在C++98的时候，C++内部并没有封装与多线程有关的API，只能通过Boost线程库来进行多线程编程，但在C++11以后就出现了std::thread这个线程类。如下是C++11多线程相关的知识点：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210947901.png"
        data-srcset="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210947901.png, https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210947901.png 1.5x, https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210947901.png 2x"
        data-sizes="auto"
        alt="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210947901.png"
        title="image-20220821094708835" /></p>
<h2 id="stdchrono标准时间库">std::chrono标准时间库</h2>
<p>C++11中提供了日期和时间相关的库chrono，通过chrono库可以很方便地处理日期和时间，为程序开发提供了便利。chrono库主要包含三种类型的类：<strong>时间间隔duration、时clock、时间点timepoint。</strong></p>
<h2 id="1时间间隔duration">1、时间间隔duration</h2>
<p>duration表示一段时间间隔，用来记录时间的长度，可以表示几秒、几分钟、几个小时的时间间隔。</p>
<p>duration原型如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="c1">// 定义于头文件 &lt;chrono&gt;
</span><span class="c1"></span><span class="k">template</span><span class="o">&lt;</span>
    <span class="k">class</span> <span class="nc">Rep</span><span class="p">,</span>
    <span class="k">class</span> <span class="nc">Period</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">ratio</span><span class="o">&lt;</span><span class="mi">1</span><span class="o">&gt;</span>
<span class="o">&gt;</span> <span class="k">class</span> <span class="nc">duration</span><span class="p">;</span>
</code></pre></div><ul>
<li>Rep：这是一个数值类型，表示时钟数（周期）的类型（默认为整形）。若 Rep 是浮点数，则 duration 能使用小数描述时钟周期的数目。</li>
<li>Period:表示时钟的周期，它的原型如下：</li>
</ul>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="c1">// 定义于头文件 &lt;ratio&gt;
</span><span class="c1"></span><span class="k">template</span><span class="o">&lt;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">intmax_t</span> <span class="n">Num</span><span class="p">,</span>
    <span class="n">std</span><span class="o">::</span><span class="n">intmax_t</span> <span class="n">Denom</span> <span class="o">=</span> <span class="mi">1</span>
<span class="o">&gt;</span> <span class="k">class</span> <span class="nc">ratio</span><span class="p">;</span>
</code></pre></div><p><strong>ratio</strong> 类表示<strong>每个时钟周期的秒数</strong>，其中第一个模板参数 <strong>Num代表分子</strong>，<strong>Denom代表分母</strong>，该分母值默认为 1，因此，**ratio代表的是一个分子除以分母的数值，**比如：ratio&lt;2&gt; 代表一个时钟周期是 2 秒，ratio&lt;60 &gt; 代表一分钟，ratio&lt;60<em>60 &gt; 代表一个小时，ratio&lt;60</em>60*24 &gt; 代表一天。而 ratio&lt;1,1000 &gt; 代表的是 1/1000 秒，也就是 1 毫秒，ratio&lt;1,1000000 &gt; 代表一微秒，ratio&lt;1,1000000000 &gt; 代表一纳秒。</p>
<p>为了方便使用，在标准库中定义了一些常用的时间间隔，比如：时、分、秒、毫秒、微秒、纳秒，它们都位于 chrono 命名空间下，定义如下：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210958336.png"
        data-srcset="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210958336.png, https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210958336.png 1.5x, https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210958336.png 2x"
        data-sizes="auto"
        alt="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208210958336.png"
        title="image-20220821095856280" /></p>
<p>duration类的构造函数原型如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="c1">// 1. 拷贝构造函数
</span><span class="c1"></span><span class="n">duration</span><span class="p">(</span> <span class="k">const</span> <span class="n">duration</span><span class="o">&amp;</span> <span class="p">)</span> <span class="o">=</span> <span class="k">default</span><span class="p">;</span>
<span class="c1">// 2. 通过指定时钟周期的类型来构造对象
</span><span class="c1"></span><span class="k">template</span><span class="o">&lt;</span> <span class="k">class</span> <span class="nc">Rep2</span> <span class="o">&gt;</span>
<span class="k">constexpr</span> <span class="k">explicit</span> <span class="n">duration</span><span class="p">(</span> <span class="k">const</span> <span class="n">Rep2</span><span class="o">&amp;</span> <span class="n">r</span> <span class="p">);</span>
<span class="c1">// 3. 通过指定时钟周期类型，和时钟周期长度来构造对象
</span><span class="c1"></span><span class="k">template</span><span class="o">&lt;</span> <span class="k">class</span> <span class="nc">Rep2</span><span class="p">,</span> <span class="k">class</span> <span class="nc">Period2</span> <span class="o">&gt;</span>
<span class="k">constexpr</span> <span class="n">duration</span><span class="p">(</span> <span class="k">const</span> <span class="n">duration</span><span class="o">&lt;</span><span class="n">Rep2</span><span class="p">,</span><span class="n">Period2</span><span class="o">&gt;&amp;</span> <span class="n">d</span> <span class="p">);</span>
</code></pre></div><p>下面是对duration类的使用代码：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span> <span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp"></span><span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">chrono</span><span class="o">::</span><span class="n">hours</span> <span class="n">h</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>                          <span class="c1">// 一小时
</span><span class="c1"></span>    <span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span> <span class="n">ms</span><span class="p">{</span> <span class="mi">3</span> <span class="p">};</span>                <span class="c1">// 3 毫秒
</span><span class="c1"></span>    <span class="n">chrono</span><span class="o">::</span><span class="n">duration</span><span class="o">&lt;</span><span class="kt">int</span><span class="p">,</span> <span class="n">ratio</span><span class="o">&lt;</span><span class="mi">1000</span><span class="o">&gt;&gt;</span> <span class="n">ks</span><span class="p">(</span><span class="mi">3</span><span class="p">);</span>    <span class="c1">// 3000 秒
</span><span class="c1"></span>
    <span class="c1">// chrono::duration&lt;int, ratio&lt;1000&gt;&gt; d3(3.5);  // error
</span><span class="c1"></span>    <span class="n">chrono</span><span class="o">::</span><span class="n">duration</span><span class="o">&lt;</span><span class="kt">double</span><span class="o">&gt;</span> <span class="n">dd</span><span class="p">(</span><span class="mf">6.6</span><span class="p">);</span>               <span class="c1">// 6.6 秒
</span><span class="c1"></span>
    <span class="c1">// 使用小数表示时钟周期的次数
</span><span class="c1"></span>    <span class="n">chrono</span><span class="o">::</span><span class="n">duration</span><span class="o">&lt;</span><span class="kt">double</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">ratio</span><span class="o">&lt;</span><span class="mi">1</span><span class="p">,</span> <span class="mi">30</span><span class="o">&gt;&gt;</span> <span class="n">hz</span><span class="p">(</span><span class="mf">3.5</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div><ul>
<li>
<p>h(1) 时钟周期为 1 小时，共有 1 个时钟周期，所以 h 表示的时间间隔为 1 小时</p>
</li>
<li>
<p>ms(3) 时钟周期为 1 毫秒，共有 3 个时钟周期，所以 ms 表示的时间间隔为 3 毫秒</p>
</li>
<li>
<p>ks(3) 时钟周期为 1000 秒，一共有三个时钟周期，所以 ks 表示的时间间隔为 3000 秒</p>
</li>
<li>
<p>d3(3.5) 时钟周期为 1000 秒，时钟周期数量只能用整形来表示，但是此处指定的是浮点数，因此语法错误</p>
</li>
<li>
<p>dd(6.6) 时钟周期为默认的 1 秒，共有 6.6 个时钟周期，所以 dd 表示的时间间隔为 6.6 秒</p>
</li>
<li>
<p>hz(3.5) 时钟周期为 1/30 秒，共有 3.5 个时钟周期，所以 hz 表示的时间间隔为 1/30*3.5 秒</p>
</li>
</ul>
<p>chrono库中根据duration类封装了不同长度的时钟周期(可以自定义),基于这个时钟周期再进行周期次数的设置可以得到总的时间间隔(时钟周期 * 周期次数 = 总的时间间隔)。</p>
<p>示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span> <span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp"></span><span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span> <span class="n">ms</span><span class="p">{</span><span class="mi">3</span><span class="p">};</span>         <span class="c1">// 3 毫秒
</span><span class="c1"></span>    <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">microseconds</span> <span class="n">us</span> <span class="o">=</span> <span class="mi">2</span><span class="o">*</span><span class="n">ms</span><span class="p">;</span>     <span class="c1">// 6000 微秒
</span><span class="c1"></span>    <span class="c1">// 时间间隔周期为 1/30 秒
</span><span class="c1"></span>    <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">duration</span><span class="o">&lt;</span><span class="kt">double</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">ratio</span><span class="o">&lt;</span><span class="mi">1</span><span class="p">,</span> <span class="mi">30</span><span class="o">&gt;&gt;</span> <span class="n">hz</span><span class="p">(</span><span class="mf">3.5</span><span class="p">);</span>
 
    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span>  <span class="s">&#34;3 ms duration has &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">ms</span><span class="p">.</span><span class="n">count</span><span class="p">()</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; ticks</span><span class="se">\n</span><span class="s">&#34;</span>
              <span class="o">&lt;&lt;</span>  <span class="s">&#34;6000 us duration has &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">us</span><span class="p">.</span><span class="n">count</span><span class="p">()</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; ticks</span><span class="se">\n</span><span class="s">&#34;</span>
              <span class="o">&lt;&lt;</span>  <span class="s">&#34;3.5 hz duration has &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">hz</span><span class="p">.</span><span class="n">count</span><span class="p">()</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; ticks</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span>       
<span class="p">}</span>
</code></pre></div><ul>
<li>ms 时间单位为毫秒，初始化操作 ms{3} 表示时间间隔为 3 毫秒，一共有 3 个时间周期，每个周期为 1 毫秒</li>
<li>us 时间单位为微秒，初始化操作 2*ms 表示时间间隔为 6000 微秒，一共有 6000 个时间周期，每个周期为 1 微秒</li>
<li>hz 时间单位为秒，初始化操作 hz(3.5) 表示时间间隔为 1/30*3.5 秒，一共有 3.5 个时间周期，每个周期为 1/30 秒</li>
</ul>
<p>由于在 duration 类内部做了操作符重载，因此时间间隔之间可以直接进行算术运算，比如我们要计算两个时间间隔的差值，就可以在代码中做如下处理：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp"></span><span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span>

<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">chrono</span><span class="o">::</span><span class="n">minutes</span> <span class="n">t1</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span>
    <span class="n">chrono</span><span class="o">::</span><span class="n">seconds</span> <span class="n">t2</span><span class="p">(</span><span class="mi">60</span><span class="p">);</span>
    <span class="n">chrono</span><span class="o">::</span><span class="n">seconds</span> <span class="n">t3</span> <span class="o">=</span> <span class="n">t1</span> <span class="o">-</span> <span class="n">t2</span><span class="p">;</span>
    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="n">t3</span><span class="p">.</span><span class="n">count</span><span class="p">()</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; second&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>在上面的测试程序中，t1 代表 10 分钟，t2 代表 60 秒，t3 是 t1 减去 t2，也就是 60*10-60=540，这个 540 表示的时钟周期，每个时钟周期是 1 秒，因此两个时间间隔之间的差值为 540 秒。</p>
<h2 id="2时间点time_point">2、时间点time_point</h2>
<p>chrono库中提供了一个表示时间点的类time_point，该类的定义如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="c1">// 定义于头文件 &lt;chrono&gt;
</span><span class="c1"></span><span class="k">template</span><span class="o">&lt;</span>
    <span class="k">class</span> <span class="nc">Clock</span><span class="p">,</span>
    <span class="k">class</span> <span class="nc">Duration</span> <span class="o">=</span> <span class="k">typename</span> <span class="n">Clock</span><span class="o">::</span><span class="n">duration</span>
<span class="o">&gt;</span> <span class="k">class</span> <span class="nc">time_point</span><span class="p">;</span>
</code></pre></div><p>它被实现成如同存储一个 Duration 类型的自 Clock 的纪元起始开始的时间间隔的值，通过这个类最终可以得到时间中的某一个时间点。</p>
<ul>
<li>Clock：此时间点在此时钟上计量</li>
<li>Duration：用于计量从纪元起时间的 std::chrono::duration 类型</li>
</ul>
<p>time_point的构造函数原型如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="c1">// 1. 构造一个以新纪元(epoch，即：1970.1.1)作为值的对象，需要和时钟类一起使用，不能单独使用该无参构造函数
</span><span class="c1"></span><span class="n">time_point</span><span class="p">();</span>
<span class="c1">// 2. 构造一个对象，表示一个时间点，其中d的持续时间从epoch开始，需要和时钟类一起使用，不能单独使用该构造函数
</span><span class="c1"></span><span class="k">explicit</span> <span class="nf">time_point</span><span class="p">(</span> <span class="k">const</span> <span class="n">duration</span><span class="o">&amp;</span> <span class="n">d</span> <span class="p">);</span>
<span class="c1">// 3. 拷贝构造函数，构造与t相同时间点的对象，使用的时候需要指定模板参数
</span><span class="c1"></span><span class="k">template</span><span class="o">&lt;</span> <span class="k">class</span> <span class="nc">Duration2</span> <span class="o">&gt;</span>
<span class="n">time_point</span><span class="p">(</span> <span class="k">const</span> <span class="n">time_point</span><span class="o">&lt;</span><span class="n">Clock</span><span class="p">,</span><span class="n">Duration2</span><span class="o">&gt;&amp;</span> <span class="n">t</span> <span class="p">);</span>
</code></pre></div><h2 id="3时钟clocks">3、时钟clocks</h2>
<p>chrono 库中提供了获取当前的系统时间的时钟类，包含的时钟一共有三种：</p>
<ul>
<li>system_clock：系统的时钟，系统的时钟可以修改，甚至可以网络对时，因此使用系统时间计算时间差可能不准。</li>
<li>steady_clock：是固定的时钟，相当于秒表。开始计时后，时间只会增长并且不能修改，适合用于记录程序耗时</li>
<li>high_resolution_clock：和时钟类 steady_clock 是等价的（是它的别名）。</li>
</ul>
<h2 id="31system_clock">3.1、system_clock</h2>
<p>具体来说，时钟类 system_clock 是一个系统范围的实时时钟。system_clock 提供了对当前时间点 time_point 的访问，将得到时间点转换为 time_t 类型的时间对象，就可以基于这个时间对象获取到当前的时间信息了。</p>
<p>system_clock 时钟类在底层源码中的定义如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="k">struct</span> <span class="nc">system_clock</span> <span class="p">{</span> <span class="c1">// wraps GetSystemTimePreciseAsFileTime/GetSystemTimeAsFileTime
</span><span class="c1"></span>    <span class="k">using</span> <span class="n">rep</span>                       <span class="o">=</span> <span class="kt">long</span> <span class="kt">long</span><span class="p">;</span>
    <span class="k">using</span> <span class="n">period</span>                    <span class="o">=</span> <span class="n">ratio</span><span class="o">&lt;</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10&#39;000&#39;000</span><span class="o">&gt;</span><span class="p">;</span> <span class="c1">// 100 nanoseconds
</span><span class="c1"></span>    <span class="k">using</span> <span class="n">duration</span>                  <span class="o">=</span> <span class="n">chrono</span><span class="o">::</span><span class="n">duration</span><span class="o">&lt;</span><span class="n">rep</span><span class="p">,</span> <span class="n">period</span><span class="o">&gt;</span><span class="p">;</span>
    <span class="k">using</span> <span class="n">time_point</span>                <span class="o">=</span> <span class="n">chrono</span><span class="o">::</span><span class="n">time_point</span><span class="o">&lt;</span><span class="n">system_clock</span><span class="o">&gt;</span><span class="p">;</span>
    <span class="k">static</span> <span class="k">constexpr</span> <span class="kt">bool</span> <span class="n">is_steady</span> <span class="o">=</span> <span class="nb">false</span><span class="p">;</span>

    <span class="n">_NODISCARD</span> <span class="k">static</span> <span class="n">time_point</span> <span class="nf">now</span><span class="p">()</span> <span class="k">noexcept</span> 
    <span class="p">{</span> <span class="c1">// get current time
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">time_point</span><span class="p">(</span><span class="n">duration</span><span class="p">(</span><span class="n">_Xtime_get_ticks</span><span class="p">()));</span>
    <span class="p">}</span>

    <span class="n">_NODISCARD</span> <span class="k">static</span> <span class="n">__time64_t</span> <span class="nf">to_time_t</span><span class="p">(</span><span class="k">const</span> <span class="n">time_point</span><span class="o">&amp;</span> <span class="n">_Time</span><span class="p">)</span> <span class="k">noexcept</span> 
    <span class="p">{</span> <span class="c1">// convert to __time64_t
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">duration_cast</span><span class="o">&lt;</span><span class="n">seconds</span><span class="o">&gt;</span><span class="p">(</span><span class="n">_Time</span><span class="p">.</span><span class="n">time_since_epoch</span><span class="p">()).</span><span class="n">count</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="n">_NODISCARD</span> <span class="k">static</span> <span class="n">time_point</span> <span class="nf">from_time_t</span><span class="p">(</span><span class="n">__time64_t</span> <span class="n">_Tm</span><span class="p">)</span> <span class="k">noexcept</span> 
    <span class="p">{</span> <span class="c1">// convert from __time64_t
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">time_point</span><span class="p">{</span><span class="n">seconds</span><span class="p">{</span><span class="n">_Tm</span><span class="p">}};</span>
    <span class="p">}</span>
<span class="p">};</span>
</code></pre></div><p>通过以上源码可以了解到在 system_clock 类中的一些细节信息：</p>
<ul>
<li>rep：时钟周期次数是通过整形来记录的 long long</li>
<li>period：一个时钟周期是 100 纳秒 ratio&lt;1, 10'000'000&gt;</li>
<li>duration：时间间隔为 rep*period 纳秒 chrono::duration&lt;rep, period&gt;</li>
<li>time_point：时间点通过系统时钟做了初始化 chrono::time_point&lt;system_clock&gt;，里面记录了新纪元时间点</li>
</ul>
<p>另外还可以看到 system_clock 类一共提供了三个静态成员函数：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="c1">// 返回表示当前时间的时间点。
</span><span class="c1"></span><span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">time_point</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">system_clock</span><span class="o">&gt;</span> <span class="n">now</span><span class="p">()</span> <span class="k">noexcept</span><span class="p">;</span>
<span class="c1">// 将 time_point 时间点类型转换为 std::time_t 类型
</span><span class="c1"></span><span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">time_t</span> <span class="n">to_time_t</span><span class="p">(</span> <span class="k">const</span> <span class="n">time_point</span><span class="o">&amp;</span> <span class="n">t</span> <span class="p">)</span> <span class="k">noexcept</span><span class="p">;</span>
<span class="c1">// 将 std::time_t 类型转换为 time_point 时间点类型
</span><span class="c1"></span><span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">system_clock</span><span class="o">::</span><span class="n">time_point</span> <span class="n">from_time_t</span><span class="p">(</span> <span class="n">std</span><span class="o">::</span><span class="n">time_t</span> <span class="n">t</span> <span class="p">)</span> <span class="k">noexcept</span><span class="p">;</span>
</code></pre></div><p>比如，我们要获取当前的系统时间，并且需要将其以能够识别的方式打印出来，示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span> <span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp"></span><span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span>
<span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="p">;</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// 新纪元1970.1.1时间
</span><span class="c1"></span>    <span class="n">system_clock</span><span class="o">::</span><span class="n">time_point</span> <span class="n">epoch</span><span class="p">;</span>

    <span class="n">duration</span><span class="o">&lt;</span><span class="kt">int</span><span class="p">,</span> <span class="n">ratio</span><span class="o">&lt;</span><span class="mi">60</span><span class="o">*</span><span class="mi">60</span><span class="o">*</span><span class="mi">24</span><span class="o">&gt;&gt;</span> <span class="n">day</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
    <span class="c1">// 新纪元1970.1.1时间 + 1天
</span><span class="c1"></span>    <span class="n">system_clock</span><span class="o">::</span><span class="n">time_point</span> <span class="n">ppt</span><span class="p">(</span><span class="n">day</span><span class="p">);</span>

    <span class="k">using</span> <span class="n">dday</span> <span class="o">=</span> <span class="n">duration</span><span class="o">&lt;</span><span class="kt">int</span><span class="p">,</span> <span class="n">ratio</span><span class="o">&lt;</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">24</span><span class="o">&gt;&gt;</span><span class="p">;</span>
    <span class="c1">// 新纪元1970.1.1时间 + 10天
</span><span class="c1"></span>    <span class="n">time_point</span><span class="o">&lt;</span><span class="n">system_clock</span><span class="p">,</span> <span class="n">dday</span><span class="o">&gt;</span> <span class="n">t</span><span class="p">(</span><span class="n">dday</span><span class="p">(</span><span class="mi">10</span><span class="p">));</span>

    <span class="c1">// 系统当前时间
</span><span class="c1"></span>    <span class="n">system_clock</span><span class="o">::</span><span class="n">time_point</span> <span class="n">today</span> <span class="o">=</span> <span class="n">system_clock</span><span class="o">::</span><span class="n">now</span><span class="p">();</span>
    
    <span class="c1">// 转换为time_t时间类型
</span><span class="c1"></span>    <span class="n">time_t</span> <span class="n">tm</span> <span class="o">=</span> <span class="n">system_clock</span><span class="o">::</span><span class="n">to_time_t</span><span class="p">(</span><span class="n">today</span><span class="p">);</span>
    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;今天的日期是:    &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">ctime</span><span class="p">(</span><span class="o">&amp;</span><span class="n">tm</span><span class="p">);</span>

    <span class="n">time_t</span> <span class="n">tm1</span> <span class="o">=</span> <span class="n">system_clock</span><span class="o">::</span><span class="n">to_time_t</span><span class="p">(</span><span class="n">today</span><span class="o">+</span><span class="n">day</span><span class="p">);</span>
    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;明天的日期是:    &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">ctime</span><span class="p">(</span><span class="o">&amp;</span><span class="n">tm1</span><span class="p">);</span>

    <span class="n">time_t</span> <span class="n">tm2</span> <span class="o">=</span> <span class="n">system_clock</span><span class="o">::</span><span class="n">to_time_t</span><span class="p">(</span><span class="n">epoch</span><span class="p">);</span>
    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;新纪元时间:      &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">ctime</span><span class="p">(</span><span class="o">&amp;</span><span class="n">tm2</span><span class="p">);</span>

    <span class="n">time_t</span> <span class="n">tm3</span> <span class="o">=</span> <span class="n">system_clock</span><span class="o">::</span><span class="n">to_time_t</span><span class="p">(</span><span class="n">ppt</span><span class="p">);</span>
    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;新纪元时间+1天:  &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">ctime</span><span class="p">(</span><span class="o">&amp;</span><span class="n">tm3</span><span class="p">);</span>

    <span class="n">time_t</span> <span class="n">tm4</span> <span class="o">=</span> <span class="n">system_clock</span><span class="o">::</span><span class="n">to_time_t</span><span class="p">(</span><span class="n">t</span><span class="p">);</span>
    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;新纪元时间+10天: &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">ctime</span><span class="p">(</span><span class="o">&amp;</span><span class="n">tm4</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div><h2 id="32-steady_clock">3.2 、steady_clock</h2>
<p>如果我们通过时钟不是为了获取当前的系统时间，而是进行程序耗时的时长，此时使用 syetem_clock 就不合适了，因为这个时间可以跟随系统的设置发生变化。在 C++11 中提供的时钟类 steady_clock 相当于秒表，只要启动就会进行时间的累加，并且不能被修改，非常适合于进行耗时的统计。</p>
<p>steady_clock 时钟类在底层源码中的定义如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="k">struct</span> <span class="nc">steady_clock</span> <span class="p">{</span> <span class="c1">// wraps QueryPerformanceCounter
</span><span class="c1"></span>    <span class="k">using</span> <span class="n">rep</span>                       <span class="o">=</span> <span class="kt">long</span> <span class="kt">long</span><span class="p">;</span>
    <span class="k">using</span> <span class="n">period</span>                    <span class="o">=</span> <span class="n">nano</span><span class="p">;</span>
    <span class="k">using</span> <span class="n">duration</span>                  <span class="o">=</span> <span class="n">nanoseconds</span><span class="p">;</span>
    <span class="k">using</span> <span class="n">time_point</span>                <span class="o">=</span> <span class="n">chrono</span><span class="o">::</span><span class="n">time_point</span><span class="o">&lt;</span><span class="n">steady_clock</span><span class="o">&gt;</span><span class="p">;</span>
    <span class="k">static</span> <span class="k">constexpr</span> <span class="kt">bool</span> <span class="n">is_steady</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>

    <span class="c1">// get current time
</span><span class="c1"></span>    <span class="n">_NODISCARD</span> <span class="k">static</span> <span class="n">time_point</span> <span class="nf">now</span><span class="p">()</span> <span class="k">noexcept</span> 
    <span class="p">{</span> 
        <span class="c1">// doesn&#39;t change after system boot
</span><span class="c1"></span>        <span class="k">const</span> <span class="kt">long</span> <span class="kt">long</span> <span class="n">_Freq</span> <span class="o">=</span> <span class="n">_Query_perf_frequency</span><span class="p">();</span> 
        <span class="k">const</span> <span class="kt">long</span> <span class="kt">long</span> <span class="n">_Ctr</span>  <span class="o">=</span> <span class="n">_Query_perf_counter</span><span class="p">();</span>
        <span class="k">static_assert</span><span class="p">(</span><span class="n">period</span><span class="o">::</span><span class="n">num</span> <span class="o">==</span> <span class="mi">1</span><span class="p">,</span> <span class="s">&#34;This assumes period::num == 1.&#34;</span><span class="p">);</span>
        <span class="k">const</span> <span class="kt">long</span> <span class="kt">long</span> <span class="n">_Whole</span> <span class="o">=</span> <span class="p">(</span><span class="n">_Ctr</span> <span class="o">/</span> <span class="n">_Freq</span><span class="p">)</span> <span class="o">*</span> <span class="n">period</span><span class="o">::</span><span class="n">den</span><span class="p">;</span>
        <span class="k">const</span> <span class="kt">long</span> <span class="kt">long</span> <span class="n">_Part</span>  <span class="o">=</span> <span class="p">(</span><span class="n">_Ctr</span> <span class="o">%</span> <span class="n">_Freq</span><span class="p">)</span> <span class="o">*</span> <span class="n">period</span><span class="o">::</span><span class="n">den</span> <span class="o">/</span> <span class="n">_Freq</span><span class="p">;</span>
        <span class="k">return</span> <span class="n">time_point</span><span class="p">(</span><span class="n">duration</span><span class="p">(</span><span class="n">_Whole</span> <span class="o">+</span> <span class="n">_Part</span><span class="p">));</span>
    <span class="p">}</span>
<span class="p">};</span>
</code></pre></div><p>通过以上源码可以了解到在 steady_clock 类中的一些细节信息：</p>
<ul>
<li>rep：时钟周期次数是通过整形来记录的 long long</li>
<li>period：一个时钟周期是 1 纳秒 nano</li>
<li>duration：时间间隔为 1 纳秒 nanoseconds</li>
<li>time_point：时间点通过系统时钟做了初始化 chrono::time_point&lt;steady_clock&gt;</li>
</ul>
<p>另外，在这个类中也提供了一个静态的 now () 方法，用于得到当前的时间点，函数原型如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">time_point</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">steady_clock</span><span class="o">&gt;</span> <span class="n">now</span><span class="p">()</span> <span class="k">noexcept</span><span class="p">;</span>
</code></pre></div><p>下面是一个简单的计算时间花费的例子：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp"></span><span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="c1">//获取当前时间点
</span><span class="c1"></span>	<span class="k">auto</span> <span class="n">t0</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">steady_clock</span><span class="o">::</span><span class="n">now</span><span class="p">();</span>
	<span class="c1">//线程阻塞；所花费的时间
</span><span class="c1"></span>	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10000000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">);</span>
	<span class="c1">//阻塞后，当前的时间点
</span><span class="c1"></span>	<span class="k">auto</span> <span class="n">t1</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">steady_clock</span><span class="o">::</span><span class="n">now</span><span class="p">();</span>
	<span class="c1">//获取两个时间点的差值
</span><span class="c1"></span>	<span class="k">auto</span> <span class="n">dt</span> <span class="o">=</span> <span class="n">t1</span> <span class="o">-</span> <span class="n">t0</span><span class="p">;</span>
	<span class="c1">//将时间点的差值转化为毫秒
</span><span class="c1"></span>	<span class="k">auto</span> <span class="n">t2</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">duration_cast</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span><span class="o">&gt;</span><span class="p">(</span><span class="n">dt</span><span class="p">).</span><span class="n">count</span><span class="p">();</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;time elapsed:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">t2</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;ms&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>上面的代码使计算整形的时间花费下面是double类型的时间花费：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp"></span><span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    	<span class="cm">/*CPP多线程与并发-time02：显示double类型的时间段
</span><span class="cm">	时间段：作为double类型
</span><span class="cm">	duration_cast可以在任意duration之间转换。
</span><span class="cm">	duration&lt;T,R&gt;,用T表示类型，R表示单位，R省略不写就是秒,std::milli就是毫秒,std::micro就是微秒
</span><span class="cm">	seconds是duration&lt;int64_t&gt;类型的别名。
</span><span class="cm">	milliseconds是duration&lt;int64_t,std::milli&gt;类型的别名
</span><span class="cm">	这里我们创建double_ms是duration&lt;double,std::milli&gt;类型的别名。
</span><span class="cm">	*/</span>
    <span class="k">auto</span> <span class="n">t0</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">steady_clock</span><span class="o">::</span><span class="n">now</span><span class="p">();</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10000000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">);</span>
	<span class="k">auto</span> <span class="n">t1</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">steady_clock</span><span class="o">::</span><span class="n">now</span><span class="p">();</span>
	<span class="k">auto</span> <span class="n">dt</span> <span class="o">=</span> <span class="n">t1</span> <span class="o">-</span> <span class="n">t0</span><span class="p">;</span>
	<span class="k">using</span> <span class="n">double_ms</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">duration</span><span class="o">&lt;</span><span class="kt">double</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">milli</span><span class="o">&gt;</span><span class="p">;</span>
	<span class="kt">double</span> <span class="n">ms</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">duration_cast</span><span class="o">&lt;</span><span class="n">double_ms</span><span class="o">&gt;</span><span class="p">(</span><span class="n">dt</span><span class="p">).</span><span class="n">count</span><span class="p">();</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;time elapsed:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">ms</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;ms&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><h2 id="4duration_cast">4、duration_cast</h2>
<p>duration_cast 是 chrono 库提供的一个模板函数，这个函数不属于 duration 类。通过这个函数可以对 duration 类对象内部的时钟周期 Period，和周期次数的类型 Rep 进行修改，该函数原型如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="k">template</span> <span class="o">&lt;</span><span class="k">class</span> <span class="nc">ToDuration</span><span class="p">,</span> <span class="k">class</span> <span class="nc">Rep</span><span class="p">,</span> <span class="k">class</span> <span class="nc">Period</span><span class="o">&gt;</span>
  <span class="k">constexpr</span> <span class="n">ToDuration</span> <span class="n">duration_cast</span> <span class="p">(</span><span class="k">const</span> <span class="n">duration</span><span class="o">&lt;</span><span class="n">Rep</span><span class="p">,</span><span class="n">Period</span><span class="o">&gt;&amp;</span> <span class="n">dtn</span><span class="p">);</span>
</code></pre></div><p><strong>如果是对时钟周期进行转换：源时钟周期必须能够整除目的时钟周期（比如：小时到分钟）。</strong>
<strong>如果是对时钟周期次数的类型进行转换：低等类型默认可以向高等类型进行转换（比如：int 转 double）。</strong>
<strong>如果时钟周期和时钟周期次数类型都变了，根据第二点进行推导（也就是看时间周期次数类型）。</strong>
<strong>以上条件都不满足，那么就需要使用 duration_cast 进行显示转换。</strong></p>
</div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4%E5%BA%93chrono/">标准时间库chrono</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-08-21</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" data-title="标准时间库chrono" data-hashtags="标准时间库chrono"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" data-hashtag="标准时间库chrono"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" data-title="标准时间库chrono" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" data-title="标准时间库chrono"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" data-title="标准时间库chrono" data-image="https://img-blog.csdnimg.cn/img_convert/2319540b52ba53f88ff0afbf5cabb92c.png#pic_center"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" data-title="标准时间库chrono" data-description="标准时间库与thread"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" data-title="标准时间库chrono" data-description="标准时间库与thread"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" data-title="标准时间库chrono"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/%C3%A5-%C3%A4%C2%BA%C3%A6%C2%BA%C3%A8%C3%A6%C3%A9/" class="prev" rel="prev" title="共享智能指针"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/thread%C3%A7%C3%A4%C3%A7/" class="next" rel="next" title="thread的使用">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2022</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
